package com.pig4cloud.pig.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.vo.UserVO;
import com.pig4cloud.pig.admin.mapper.SysUserMapper;
import com.pig4cloud.pig.admin.mq.MqttMessageSender;
import com.pig4cloud.pig.admin.mq.vo.LockDataVo;
import com.pig4cloud.pig.admin.mq.vo.SendRequestVo;
import com.pig4cloud.pig.admin.service.SysUserService;
import com.pig4cloud.pig.common.core.util.R;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备发送指令
 * @author lh
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/prDevice/instruction" )
@Tag(description = "PrDeviceInstruction" , name = "设备发送指令" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class PrDeviceInstructionController {

	private final MqttMessageSender mqttMessageSender;
	private final SysUserService sysUserService;
	private final SysUserMapper sysUserMapper;
	@Value("${spring.mqtt.devTopic}")
	private String topic;
	/**
	 * 解锁
	 * @return
	 */
	@GetMapping("unlock")
	public R unlock(@RequestParam String clientId,@RequestParam String devName) {
		LockDataVo lockDataVo = new LockDataVo();
		lockDataVo.setDeviceid(clientId);
		lockDataVo.setDevicename(devName);
		lockDataVo.setType("unlock");
		//获取当前用户绑定的柜体用户
		String userId = getUserId(clientId);
		if(StringUtils.isBlank(userId)){
			return R.failed("当前用户没有设备权限");
		}
		lockDataVo.setUserId(userId);
		SendRequestVo sendRequestVo = new SendRequestVo();
		sendRequestVo.setData(lockDataVo);
		sendRequestVo.setDeviceid(clientId);
		sendRequestVo.setType("send");
		sendRequestVo.setCmdtype("02");
		String sendTopic = String.format(topic, clientId);
		mqttMessageSender.send(sendTopic, JSONObject.toJSONString(sendRequestVo));
		return R.ok();
	}
	/**
	 * 锁定
	 * @return
	 */
	@GetMapping("lock")
	public R lock(@RequestParam String clientId,@RequestParam String devName) {

		LockDataVo lockDataVo = new LockDataVo();
		lockDataVo.setDeviceid(clientId);
		lockDataVo.setDevicename(devName);
		lockDataVo.setType("lock");
		//获取用户信息
		//获取当前用户绑定的柜体用户
		String userId = getUserId(clientId);
		if(StringUtils.isBlank(userId)){
			return R.failed("当前用户没有设备权限");
		}
		lockDataVo.setUserId(userId);
		SendRequestVo sendRequestVo = new SendRequestVo();
		sendRequestVo.setData(lockDataVo);
		sendRequestVo.setDeviceid(clientId);
		sendRequestVo.setType("send");
		sendRequestVo.setCmdtype("01");
		String sendTopic = String.format(topic, clientId);
		mqttMessageSender.send(sendTopic, JSONObject.toJSONString(sendRequestVo));
		return R.ok();
	}

	@Nullable
	private String getUserId(String clientId) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysUser::getUsername, authentication.getName());
		SysUser user = sysUserService.getOne(queryWrapper);
		UserVO userVO = sysUserMapper.getUserVoById(user.getUserId());
		JSONArray prUser = userVO.getPrUser();
		if(null == prUser){
			return "";
		}
		String userId = "";
		for (int i = 0; i < prUser.size(); i++) {
			JSONArray pu = prUser.getJSONArray(i);
			String deviceSign = pu.getString(0);
			if(clientId.equals(deviceSign)){
				userId = pu.getString(1);
			}

		}
		return userId;
	}

	/**
	 * 重启
	 * @return
	 */
	@GetMapping("restart")
	public R restart(@RequestParam String clientId,@RequestParam String devName) {

		LockDataVo lockDataVo = new LockDataVo();
		lockDataVo.setDeviceid(clientId);
		lockDataVo.setDevicename(devName);
		//获取当前用户绑定的柜体用户
		String userId = getUserId(clientId);
		if(StringUtils.isBlank(userId)){
			return R.failed("当前用户没有设备权限");
		}
		lockDataVo.setUserId(userId);
		SendRequestVo sendRequestVo = new SendRequestVo();
		sendRequestVo.setData(lockDataVo);
		sendRequestVo.setDeviceid(clientId);
		sendRequestVo.setType("send");
		sendRequestVo.setCmdtype("04");
		String sendTopic = String.format(topic, clientId);
		mqttMessageSender.send(sendTopic, JSONObject.toJSONString(sendRequestVo));
		return R.ok();
	}
	/**
	 * 关机
	 * @return
	 */
	@GetMapping("shutdown")
	public R shutdown(@RequestParam String clientId,@RequestParam String devName) {

		LockDataVo lockDataVo = new LockDataVo();
		lockDataVo.setDeviceid(clientId);
		lockDataVo.setDevicename(devName);
		//获取当前用户绑定的柜体用户
		String userId = getUserId(clientId);
		if(StringUtils.isBlank(userId)){
			return R.failed("当前用户没有设备权限");
		}
		lockDataVo.setUserId(userId);
		SendRequestVo sendRequestVo = new SendRequestVo();
		sendRequestVo.setData(lockDataVo);
		sendRequestVo.setDeviceid(clientId);
		sendRequestVo.setType("send");
		sendRequestVo.setCmdtype("03");
		String sendTopic = String.format(topic, clientId);
		mqttMessageSender.send(sendTopic, JSONObject.toJSONString(sendRequestVo));
		return R.ok();
	}
	/**
	 * 开柜门
	 * @return
	 */
	@GetMapping("openDoor")
	public R openDoor(@RequestParam String clientId,@RequestParam String devName) {

		List<String> keys = new ArrayList<>();
		LockDataVo lockDataVo = new LockDataVo();
		lockDataVo.setDeviceid(clientId);
		lockDataVo.setDevicename(devName);
		//获取当前用户绑定的柜体用户
		String userId = getUserId(clientId);
		if(StringUtils.isBlank(userId)){
			return R.failed("当前用户没有设备权限");
		}
		lockDataVo.setUserId(userId);
		lockDataVo.setKeys(keys);
		SendRequestVo sendRequestVo = new SendRequestVo();
		sendRequestVo.setData(lockDataVo);
		sendRequestVo.setDeviceid(clientId);
		sendRequestVo.setType("send");
		sendRequestVo.setCmdtype("05");
		String sendTopic = String.format(topic, clientId);
		mqttMessageSender.send(sendTopic, JSONObject.toJSONString(sendRequestVo));
		return R.ok();
	}

}
